package org.csu.onlineedubackend.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.csu.onlineedubackend.dto.CourseDTO;
import org.csu.onlineedubackend.dto.StudentDetailDTO;
import org.csu.onlineedubackend.dto.TeacherDetailDTO;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.UserService;
import org.csu.onlineedubackend.service.impl.UserServiceExtImpl;
import org.csu.onlineedubackend.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Enumeration;
import java.lang.Void;
import java.lang.String;
import java.lang.Integer;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserServiceExtImpl userService2;

    @Autowired
    private FileUtil fileUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("user-info")
    public CommonResponse<User> getUserInfo(HttpServletRequest request,
                                            @RequestParam Integer userId) {
        try {
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                System.out.println(headerName + ": " + request.getHeader(headerName));
            }
            // 检查登录状态
            if (!StpUtil.isLogin()) {
//                System.out.println("用户未登录，尝试从请求头获取token");
                // 尝试从请求头中获取token
                String headerToken = request.getHeader("satoken");
                if (headerToken != null && !headerToken.isEmpty()) {
//                    System.out.println("从请求头中获取到token: " + headerToken);
                    try {
                        Object loginIdObj = StpUtil.getLoginIdByToken(headerToken);
                        if (loginIdObj != null) {

//                            System.out.println("从请求头token获取到用户ID: " + userId);
                            
                            // 从数据库查询完整用户信息
                            User user = userService.getById(userId);
                            if (user == null) {
//                                System.out.println("用户不存在，用户ID: " + userId);
                                return CommonResponse.createForError(
                                    ResponseCode.USER_NOT_EXIST.getCode(),
                                    "用户不存在"
                                );
                            }
                            
                            // 清空密码字段
                            user.setPassword(null);
//                            System.out.println("成功获取用户信息: " + user.getUsername());
                            return CommonResponse.createForSuccess(
                                ResponseCode.Success.getCode(),
                                "获取用户信息成功",
                                user
                            );
                        } else {
                            System.out.println("请求头token无效，未能获取用户ID");
                        }
                    } catch (Exception ex) {
                        System.out.println("请求头token验证失败: " + ex.getMessage());
                    }
                } else {
                    System.out.println("请求头中没有找到satoken");
                }
                
                return CommonResponse.createForError(
                    ResponseCode.NEED_LOGIN.getCode(),
                    "用户未登录"
                );
            }

            // 从数据库查询完整用户信息
            User user = userService.getById(userId);

            if (user == null) {
                System.out.println("用户不存在，用户ID: " + userId);
                return CommonResponse.createForError(
                    ResponseCode.USER_NOT_EXIST.getCode(),
                    "用户不存在"
                );
            }

            // 清空密码字段
            user.setPassword(null);
            System.out.println("成功获取用户信息: " + user.getUsername());

            return CommonResponse.createForSuccess(
                ResponseCode.Success.getCode(),
                "获取用户信息成功",
                user
            );
        } catch (NotLoginException e) {
            System.out.println("Sa-Token未登录异常: " + e.getMessage());
            return CommonResponse.createForError(
                ResponseCode.NEED_LOGIN.getCode(),
                "用户未登录: " + e.getMessage()
            );
        } catch (Exception e) {
            System.out.println("获取用户信息失败: " + e.getMessage());
            e.printStackTrace();
            return CommonResponse.createForError(
                ResponseCode.Error.getCode(),
                "获取用户信息失败: " + e.getMessage()
            );
        }
    }


    /**
     * 根據用戶ID獲取用戶信息
     */

//    @GetMapping("/getName/{userId}")
//    public CommonResponse<User> getUsernameBy(@PathVariable Integer userId) {

//    @GetMapping("/{userId}")
//    public CommonResponse<User> getUserByIdbyxia(@PathVariable Integer userId) {

//        try {
//            // 從數據庫查詢用戶信息
//            User user = userService.getById(userId);
//
//            if (user == null) {
//                return CommonResponse.createForError(
//                    ResponseCode.USER_NOT_EXIST.getCode(),
//                    "用户不存在"
//                );
//            }
//
//            // 清空密碼字段
//            user.setPassword(null);
//
//            return CommonResponse.createForSuccess(
//                ResponseCode.Success.getCode(),
//                "获取用户信息成功",
//                user
//            );
//        } catch (Exception e) {
//            e.printStackTrace();
//            return CommonResponse.createForError(
//                ResponseCode.Error.getCode(),
//                "获取用户信息失败: " + e.getMessage()
//            );
//        }
//    }


    @GetMapping("/teacher/{id}")
    public CommonResponse<TeacherDetailDTO> getTeacherDetail(
            @PathVariable Integer id
    ) {
        TeacherDetailDTO teacher = userService.getTeacherDetail(id);
        if (teacher == null) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "教师不存在");
        }
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", teacher);
    }
    
    @GetMapping("/student/{id}")
    public CommonResponse<StudentDetailDTO> getStudentDetail(
            @PathVariable Integer id
    ){
        StudentDetailDTO student = userService.getStudentDetail(id);
        if (student == null) {
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "学生不存在");
        }
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", student);
    }

    @GetMapping("/{id}")
    public CommonResponse<User> getUserById(@PathVariable Integer id) {
        User user = userService.getById(id);
        if (user == null) {
            return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "用户不存在");
        }
        user.setPassword(null); // 不返回密码
        return CommonResponse.createForSuccess(ResponseCode.Success.getCode(), "获取用户信息成功", user);
    }

    /**
     * 更新用户个人资料
     * @param username 用户名
     * @param currentPassword 当前密码
     * @param newPassword 新密码
//     * @param avatar 头像文件
//     * @param theme 主题模式
     * @return 更新结果
     */
//    @PostMapping("/update-profile")
//    @SaCheckLogin
//    public CommonResponse updateProfile(
//            @RequestParam(value = "username", required = false) String username,
//            @RequestParam(value = "currentPassword", required = false) String currentPassword,
//            @RequestParam(value = "newPassword", required = false) String newPassword,
//            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
//            @RequestParam(value = "theme", required = false) String theme) {
//
//        // 获取当前登录用户ID
//        Long userId = StpUtil.getLoginIdAsLong();
//        User user = userService2.findUserById(userId);
//
//        if (user == null) {
//            return CommonResponse.error("用户不存在");
//        }
//
//        // 更新用户名
//        if (username != null && !username.trim().isEmpty()) {
//            user.setName(username);
//        }
//
//        // 更新密码
//        if (newPassword != null && !newPassword.trim().isEmpty()) {
//            if (currentPassword == null || currentPassword.trim().isEmpty()) {
//                return CommonResponse.error("请提供当前密码");
//            }
//
//            // 验证当前密码
//            if (!userService2.checkPassword(user, currentPassword)) {
//                return CommonResponse.error("当前密码不正确");
//            }
//
//            // 更新密码
//            userService2.updatePassword(user, newPassword);
//        }
//
//        // 更新主题偏好
//        if (theme != null) {
//            // 将主题偏好保存到Redis中，设置一个较长的过期时间
//            String themeKey = "user:theme:" + userId;
//            redisTemplate.opsForValue().set(themeKey, theme, 365, TimeUnit.DAYS);
//        }
//
//        Map<String, Object> responseData = new HashMap<>();
//
//        // 处理头像上传
//        if (avatar != null && !avatar.isEmpty()) {
//            try {
//                // 使用FileUtil上传文件
//                String avatarUrl = fileUtil.uploadFile(avatar);
//
//                // 更新用户头像URL
//                user.setAvatar(avatarUrl);
//
//                responseData.put("avatarUrl", avatarUrl);
//            } catch (IOException e) {
//                return CommonResponse.error("头像上传失败: " + e.getMessage());
//            }
//        }
//
//        // 保存用户信息
//        userService2.saveUser(user);
//
//        responseData.put("username", user.getName());
//
//        return CommonResponse.success(responseData);
//    }
//
//    /**
//     * 获取用户主题设置
//     * @return 主题设置
//     */
//    @GetMapping("/theme")
//    @SaCheckLogin
//    public CommonResponse getUserTheme() {
//        Long userId = StpUtil.getLoginIdAsLong();
//        String themeKey = "user:theme:" + userId;
//
//        Object theme = redisTemplate.opsForValue().get(themeKey);
//        String themeValue = theme != null ? theme.toString() : "light";
//
//        Map<String, String> data = new HashMap<>();
//        data.put("theme", themeValue);
//
//        return CommonResponse.success(data);
//    }

    @PostMapping("/update-profile")
    @SaCheckLogin
    public CommonResponse updateProfile(
            @RequestParam(value = "username", required = false) String username,
            @RequestParam(value = "currentPassword", required = false) String currentPassword,
            @RequestParam(value = "newPassword", required = false) String newPassword)
//            @RequestParam(value = "avatar", required = false) MultipartFile avatar,
//            @RequestParam(value = "theme", required = false) String theme)
            {

        // 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userService2.findUserById(userId);

        if (user == null) {
            return CommonResponse.error("用户不存在");
        }

        // 更新用户名
        if (username != null && !username.trim().isEmpty()) {
            user.setName(username);
        }

        // 更新密码
        if (newPassword != null && !newPassword.trim().isEmpty()) {
            if (currentPassword == null || currentPassword.trim().isEmpty()) {
                return CommonResponse.error("请提供当前密码");
            }

            // 验证当前密码
            if (!userService2.checkPassword(user, currentPassword)) {
                return CommonResponse.error("当前密码不正确");
            }

            // 更新密码
            userService2.updatePassword(user, newPassword);
        }

        // 更新主题偏好
//        if (theme != null) {
//            // 将主题偏好保存到Redis中，设置一个较长的过期时间
//            String themeKey = "user:theme:" + userId;
//            redisTemplate.opsForValue().set(themeKey, theme, 365, TimeUnit.DAYS);
//        }

        Map<String, Object> responseData = new HashMap<>();

        // 处理头像上传
//        if (avatar != null && !avatar.isEmpty()) {
//            try {
//                // 使用FileUtil上传文件
//                String avatarUrl = fileUtil.uploadFile(avatar);
//
//                // 更新用户头像URL
//                user.setAvatar(avatarUrl);
//
//                responseData.put("avatarUrl", avatarUrl);
//            } catch (IOException e) {
//                return CommonResponse.error("头像上传失败: " + e.getMessage());
//            }
//        }

        // 保存用户信息
        userService2.saveUser(user);

        responseData.put("username", user.getName());

        return CommonResponse.success(responseData);
    }

    /**
     * 获取用户主题设置
     * @return 主题设置
     */
//    @GetMapping("/theme")
//    @SaCheckLogin
//    public CommonResponse getUserTheme() {
//        Long userId = StpUtil.getLoginIdAsLong();
//        String themeKey = "user:theme:" + userId;
//
//        Object theme = redisTemplate.opsForValue().get(themeKey);
//        String themeValue = theme != null ? theme.toString() : "light";
//
//        Map<String, String> data = new HashMap<>();
//        data.put("theme", themeValue);
//
//        return CommonResponse.success(data);
//    }

    @PutMapping("/profile/{studentId}")
    public CommonResponse<String> updateStudentProfile(@PathVariable Integer studentId, @RequestBody Map<String, Object> params) {
        User user = userService.getById(studentId);
        if (user == null || user.getRole() != 1) {
            return CommonResponse.createForError(ResponseCode.USER_NOT_EXIST.getCode(), "学生不存在");
        }
        // 修改基本信息
        if (params.containsKey("name")) user.setName((String) params.get("name"));
//        if (params.containsKey("username")) user.setUsername((String) params.get("username"));
//        if (params.containsKey("phone")) user.setPhone((String) params.get("phone"));

        // 修改密码（只有传了 newPassword 才处理）
        if (params.containsKey("newPassword")) {
            String oldPassword = (String) params.get("oldPassword");
            String newPassword = (String) params.get("newPassword");
            if (oldPassword == null || !user.getPassword().equals(oldPassword)) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "原密码错误");
            }
            user.setPassword(newPassword);
        }

        userService.updateById(user);
        return CommonResponse.createForSuccess(ResponseCode.Success.getCode(), "保存成功", null);
    }
}

